package com.gitee.kinbug.sso.login;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gitee.kinbug.sso.handler.TokenIdHandler;
import com.gitee.kinbug.sso.handler.TokenLoginHandler;
import com.gitee.kinbug.sso.model.AuthUser;
import com.gitee.kinbug.sso.model.Result;
import com.gitee.kinbug.sso.store.SsoServiceStore;

/**
 * sso server (for app)
 *
 * @author BianPeng 2018-04-08 21:02:54
 */
@Controller
@RequestMapping("/app")
public class AppController {

    @Autowired
    private UserService userService;


    /**
     * Login
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result<String> login(String username, String password) {

        // valid login
        Result<UserInfo> result = userService.findUser(username, password);
        if (result.getCode() != Result.SUCCESS_CODE) {
            return new Result<String>(result.getCode(), result.getMsg(), null);
        }

        // 1、make xxl-sso user
        AuthUser authUser = new AuthUser();
        authUser.setUserid(String.valueOf(result.getData().getUserid()));
        authUser.setUsername(result.getData().getUsername());
        authUser.setVersion(UUID.randomUUID().toString().replaceAll("-", ""));
        authUser.setExpireMinite(SsoServiceStore.redisExpireMinite);
        authUser.setExpireFreshTime(System.currentTimeMillis());


        // 2、generate sessionId + storeKey
        String sessionId = TokenIdHandler.makeSessionId(authUser);

        // 3、login, store storeKey
        TokenLoginHandler.login(sessionId, authUser);

        // 4、return sessionId
        return new Result<String>(sessionId);
    }


    /**
     * Logout
     *
     * @param sessionId
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public Result<String> logout(String sessionId) {
        // logout, remove storeKey
    	TokenLoginHandler.logout(sessionId);
        return Result.SUCCESS;
    }

    /**
     * logincheck
     *
     * @param sessionId
     * @return
     */
    @RequestMapping("/logincheck")
    @ResponseBody
    public Result<AuthUser> logincheck(String sessionId) {

        // logout
        AuthUser authUser = TokenLoginHandler.loginCheck(sessionId);
        if (authUser == null) {
            return new Result<AuthUser>(Result.FAIL_CODE, "sso not login.", null);
        }
        return new Result<AuthUser>(authUser);
    }

}